﻿using System;
using System.Windows.Forms;
using System.Text.RegularExpressions;


namespace SecondClassAssignment{
    public partial class BalanceWindow : Form{
        private readonly Account _account;
        private readonly ATM _atm = new ATM();

        private void Withdraw_Click(object sender, EventArgs e){
            if (!mistakeInfo.Text.Equals("") || countValue.Text.Equals(""))
                return;
            var count = double.Parse(countValue.Text.Trim());
            if(!_atm.Withdraw(count,_account))
                MessageBox.Show("输入的金额不正确,请重新输入!", "Warning", MessageBoxButtons.OK);
            InitWindow();
        }
        
        private void Save_Click(object sender, EventArgs e){
            if (!mistakeInfo.Text.Equals("") || countValue.Text.Equals(""))
                return;
            var count = double.Parse(countValue.Text.Trim());
            try {
                if(!_atm.Save(count,_account))
                    MessageBox.Show("输入的金额不正确,请重新输入!", "Warning", MessageBoxButtons.OK);
            }
            catch (BadCashException exception) {
                MessageBox.Show(exception.Message, "Warning", MessageBoxButtons.OK);
            }
            InitWindow();
        }
        private void InitWindow(){
            Welcome.Text = $"[{_account.Id}] 欢迎您!";
            balance.Text = _account.Balance.ToString();
            countValue.Text = "";
        }
        
        private void BigMoneyWarn(object sender,BigMoneyArgs e){
            MessageBox.Show("当前取款金额大于1000!", "Warning", MessageBoxButtons.OK);
        }
        

        private void MistakeInfo(object sender, EventArgs e){
            mistakeInfo.Text = "";
            var text = countValue.Text.Trim();
            if (!Regex.IsMatch(text, @"^\d+$") && text != "") // 判断字符串是否为数字 的正则表达式
                mistakeInfo.Text = "请输入正确的数字!";
        }
        
        public BalanceWindow(Account account){
            _account = account;
            InitializeComponent();
            InitWindow();
            withdraw.Click += Withdraw_Click;
            save.Click += Save_Click;
            countValue.TextChanged += MistakeInfo;
            _atm.BigMoneyFetched += BigMoneyWarn;
        }
    }
}